package com.jaya.budan.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ImageUtils;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.CommonPopWindow;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class My_Wallet_RealName_Activity extends BaseActivity implements View.OnClickListener, CommonPopWindow.ViewClickListener {

    private RelativeLayout back;
    private ImageView iv_my_wallet_real_name_1, iv_my_wallet_real_name_2, iv_my_wallet_real_name_3;
    private EditText et_my_wallet_real_name, et_my_wallet_real_name_idcard;
    private Button btn_my_wallet_real_name;
    private String access_token, currentUploadPath;
    private int type;
    private Uri photoUri;
    private static final int TAKE_PHOTO = 0;
    private static final int PICK_PHOTO = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_wallet_realname);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        back = findViewById(R.id.back);
        et_my_wallet_real_name = findViewById(R.id.et_my_wallet_real_name);
        et_my_wallet_real_name_idcard = findViewById(R.id.et_my_wallet_real_name_idcard);
        iv_my_wallet_real_name_1 = findViewById(R.id.iv_my_wallet_real_name_1);
        iv_my_wallet_real_name_2 = findViewById(R.id.iv_my_wallet_real_name_2);
        iv_my_wallet_real_name_3 = findViewById(R.id.iv_my_wallet_real_name_3);
        btn_my_wallet_real_name = findViewById(R.id.btn_my_wallet_real_name);
        back.setOnClickListener(this);
        iv_my_wallet_real_name_1.setOnClickListener(this);
        iv_my_wallet_real_name_2.setOnClickListener(this);
        iv_my_wallet_real_name_3.setOnClickListener(this);
        btn_my_wallet_real_name.setOnClickListener(this);
        et_my_wallet_real_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        et_my_wallet_real_name_idcard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                et_my_wallet_real_name_idcard.setText(s.toString().replaceAll("(\\d{4})\\d{10}(\\d{4})", "$1****$2"));//身份证号码保留前4位，后4位
            }
        });
        // android 7.0系统解决拍照的问题
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_my_wallet_real_name:
                SharedPreferences preferences = getSharedPreferences("photo_path", Context.MODE_PRIVATE);
                String path = preferences.getString("path", "");
                JSONObject object = new JSONObject();
                try {
                    object.put("name", et_my_wallet_real_name.getText().toString().trim());
                    object.put("cardNumber", et_my_wallet_real_name_idcard.getText().toString().trim());
                    if (! ToolUtils.isEmpty(path)){
                        object.put("cardFront", path);
                        object.put("cardBack", path);
                        object.put("cardHold", path);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                postData(object);
                break;
            case R.id.iv_my_wallet_real_name_1:
                type = 1;
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_my_wallet_real_name)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 464)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsBottom(v);
                break;
            case R.id.iv_my_wallet_real_name_2:
                type = 2;
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_my_wallet_real_name)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 465)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsBottom(v);
                break;
            case R.id.iv_my_wallet_real_name_3:
                type = 3;
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_my_wallet_real_name)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 466)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsBottom(v);
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     */
    private void postData(JSONObject object) {
        Log.d("wallet", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.gr_my_wallet_SMRZ_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("wallet", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        ToolUtils.showToast(My_Wallet_RealName_Activity.this, message);
                        finish();
                    } else {
                        ToolUtils.showToast(My_Wallet_RealName_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(My_Wallet_RealName_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_my_wallet_real_name:
                TextView tv_pop_real_name_photo = view.findViewById(R.id.tv_pop_real_name_photo);
                TextView tv_pop_real_name_picture = view.findViewById(R.id.tv_pop_real_name_picture);
                LinearLayout ll_pop_cancel = view.findViewById(R.id.ll_pop_cancel);
                ll_pop_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                    }
                });
                tv_pop_real_name_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        //只是加了一个uri作为地址传入
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        File photoFile = createImgFile();
                        photoUri = Uri.fromFile(photoFile);
                        cropPhoto(photoUri);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                        startActivityForResult(intent, TAKE_PHOTO);
                    }
                });
                tv_pop_real_name_picture.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        if (ContextCompat.checkSelfPermission(My_Wallet_RealName_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(My_Wallet_RealName_Activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        } else {
                            openAlbum();
                        }
                    }
                });
                break;
            default:
                break;
        }
    }

    //获取权限的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1){
            if (grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_GRANTED) openAlbum();
            else ToolUtils.showToast(My_Wallet_RealName_Activity.this,"你拒绝了");
        }
    }

    //将图片添加进手机相册
    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(photoUri);
        this.sendBroadcast(mediaScanIntent);
    }

    private void openAlbum() {
//        Intent intent = new Intent("android.intent.action.GET_CONTENT");
//        intent.setType("image/*");
//        startActivityForResult(intent, PICK_PHOTO);
        Intent intent = new Intent(My_Wallet_RealName_Activity.this, PhotoAlbum_Activity.class);
        intent.putExtra("access_token", access_token);
        intent.putExtra("bucket", "certify");
        intent.putExtra("cos_type", 2);
        startActivity(intent);
    }

    /**
     * 调用系统的裁剪
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    /**
     * 自定义图片名，获取照片的file
     */
    private File createImgFile() {
        //创建文件
        String fileName = "img_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";//确定文件名
//        File dir=getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//        File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File dir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            dir = Environment.getExternalStorageDirectory();
            dir = getExternalCacheDir();
        } else {
            dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile = new File(dir, fileName);
        try {
            if (tempFile.exists()) {
                tempFile.delete();
            }
            tempFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取文件路径
        currentUploadPath = tempFile.getAbsolutePath();
        return tempFile;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data!=null) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    galleryAddPic();
                    break;
                case PICK_PHOTO:
                    if (Build.VERSION.SDK_INT>=19)
                        handImage(data);
                    else handImageLow(data);
//                    cropPhoto(data.getData());// 裁剪图片
                    break;
                case RESULT_REQUEST_CODE:
                    Log.d("wallet", "111" + currentUploadPath);
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap head = extras.getParcelable("data");
                        if (head != null) {
                            if (type == 1){
                                iv_my_wallet_real_name_1.setImageBitmap(head);
                            } else if (type == 2){
                                iv_my_wallet_real_name_2.setImageBitmap(head);
                            } else {
                                iv_my_wallet_real_name_3.setImageBitmap(head);
                            }
                            ImageUtils.bitmapToBase64(head);//base64加密
                            try {
                                ImageUtils.saveBitmapToFile(head, currentUploadPath);
                                new PhotoAlbum_Activity().upload(currentUploadPath, "certify", access_token, My_Wallet_RealName_Activity.this, 2);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    //安卓版本大于4.4的处理方法
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handImage(Intent data){
        String path =null;
        Uri uri = data.getData();
        //根据不同的uri进行不同的解析
        if (DocumentsContract.isDocumentUri(this,uri)){
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID+"="+id;
                path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                path = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            path = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            path = uri.getPath();
        }
        //展示图片
        displayImage(path);
    }

    //安卓小于4.4的处理方法
    private void handImageLow(Intent data){
        Uri uri = data.getData();
        String path = getImagePath(uri,null);
        displayImage(path);
    }

    //content类型的uri获取图片路径的方法
    private String getImagePath(Uri uri,String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor!=null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //根据路径展示图片的方法
    private void displayImage(String imagePath){
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            iv_my_wallet_real_name_3.setImageBitmap(bitmap);
        } else {
            ToolUtils.showToast(this, "图片设置失败");
        }
    }
}
